package core.rb;

import core.aln.Reader;
import core.aln.Worker;
import core.rb.r.IR;
import core.sb.s.Seq;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;

/*Author: John Archer, Contact: john.archer.jpa@gmail.com*/
public class IB implements Serializable{
    private ArrayList <IR> irl;
    private Seq ref;
    private int[] qDist;

    public IB(){
        this.ref = null;
        this.irl = new ArrayList();
        if(!Reader.read){(new Worker(new Reader())).execute();}
    }

    public IB(Seq ref){
        this.ref = ref;
        this.irl = new ArrayList();
        if(!Reader.read){(new Worker(new Reader())).execute();}
    }

    public IB(Seq ref, ArrayList <IR> ir) {
        this.irl = ir;
        this.ref = ref;
        if(!Reader.read){(new Worker(new Reader())).execute();}
    }

    public void rm(int y){irl.remove(y);}
    public void add(IR mf) {irl.add(mf);}
    public void rpRef(String ref){this.ref.setDNA(ref);}
    public Seq getRef(){return ref;}
    public int getSize(){return irl.size();}
    public IR getRead(int n){return irl.get(n);}

    public void load(String fname){
        irl = new ArrayList();
        try {
            BufferedReader iFile = new BufferedReader(new FileReader(fname));
            boolean again = true;
            int c = 1;
            String title = "";String dna = "";String quals = "";
            do {
                try {
                    title = new String(iFile.readLine());
                    dna = new String(iFile.readLine().toUpperCase());
                    iFile.readLine();
                    quals = new String(iFile.readLine());
                    this.add(new IR(title, dna, quals, c++));
                } catch (Exception e) {again = false;}
            } while(again);
            
            iFile.close();
        } catch (Exception e){}
    }

    public void saveReads(String filename) throws Exception{
        PrintWriter outFile = new PrintWriter(new FileWriter(filename), false);
        for (int n = 0; n < irl.size(); n++){
            outFile.println(irl.get(n).getTitle());
            outFile.println(irl.get(n).getDNA());
            outFile.println("+");
            outFile.println(irl.get(n).getQuals());
        }
        outFile.close();
    }

    private void genQDist(){
        qDist = new int[150];
        String quals;
        for (int i=0; i<this.getSize(); i++) {
            quals = this.getRead(i).getQuals();
            for (int j=0; j<quals.length(); j++) {if (((int)quals.charAt(j)) < 100)qDist [((int)quals.charAt(j))]++;}
        }
    }

    public int[] getQDist() {if(qDist==null)genQDist();return qDist;}
}